/*
 * @Author: Bennent_G
 * @Date: 2024-12-23 16:14:13
 * @LastEditTime: 2025-01-17 10:54:30
 * @Description:permission hook
 */

import { h } from 'vue';
import type { MenuProps } from 'ant-design-vue';
import { IconMap, IconType } from '@/utils/icons';
import { fetchPermissionByRoleMock, fetchPermissionByRole } from '@/apis/admin/permission';

export type Permission = {
	id: number;
	parentId: number;
	name: string;
	path: string;
	icon?: string;
	children?: Permission[];
};
// type role = {
// 	roleId: number | string;
// }

const initRouter = [
	{
		id: 0,
		parentId: 0,
		name: '首页',
		path: '/admin/welcome',
		icon: 'HomeOutlined',
	},
];
const serverMode = import.meta.env.VITE_SERVER_MODE;

export function usePermission() {
	/**
	 * @description: get permissions by role id
	 * @param {role} params
	 * @return {*}
	 */
	const getPermissionByRoleId = async () => {
		const { data } = serverMode
			? await fetchPermissionByRole<Permission[]>()
			: await fetchPermissionByRoleMock<Permission[]>();
		return formatPermissions([...initRouter, ...data]);
	};

	/**
	 * @description: format permissions
	 * @param {Permission[]} permissions
	 * @return {*}
	 */
	const formatPermissions = (permissions: Permission[]): (typeof MenuProps)['items'] => {
		return permissions.map((item) => {
			const icons = resolveIcon(item.icon as IconType);
			return {
				id: item.id.toString(),
				key: item.path,
				parentId: item.parentId.toString(),
				label: item.name,
				title: item.name,
				path: item.path,
				icon: () => (icons ? h(icons) : null),
				children: item.children ? formatPermissions(item.children) : undefined,
			};
		});
	};

	/**
	 * @description: resolve icon
	 * @param {IconType} iconName
	 * @return {*}
	 */
	const resolveIcon = (iconName: IconType | undefined): any => {
		return iconName && IconMap.has(iconName) ? IconMap.get(iconName)! : null;
	};

	return {
		getPermissionByRoleId,
	};
}
